<template>
  <div class="goods-detail-caontainer" v-if="goodsInfo">
    <nut-swiper :init-page="0" :auto-play="false" pagination-visible pagination-color="#426543"
      pagination-unselected-color="#808080">
      <nut-swiper-item v-for="(item, index) in goodsInfo?.productImages" :key="index">
        <img :src="item" alt="" @click="handlePreviewImage(item)" style="object-fit: cover; height: 250px; width: 100%;"
          draggable="false" />
      </nut-swiper-item>
    </nut-swiper>
    <div class="goods-detail-content">
      <div class="price-box">
        <div class="price" v-if="goodsInfo?.productSpecials && goodsInfo?.productSpecials.length > 0">
          <nut-price :price="goodsInfo?.productSpecials[0].sellerPrice / 100" size="large" /> <span
            style="font-size: 14px;color: #999;margin-left: 5px;">起</span>
        </div>
        <div class="price" v-else>
          <nut-price :price="goodsInfo?.sellPrice / 100" size="large" />
        </div>
        <div class="stock">总库存 {{ totalStock || 0 }}</div>
      </div>
      <div class="product-title">
        {{ goodsInfo?.title }}
      </div>
      <div class="product-tags" v-if="goodsInfo?.tags?.length > 0">
        <div v-if="goodsInfo?.tags.indexOf(1) !== -1" class="tag-item">描述不符包退</div>
        <div v-if="goodsInfo?.tags.indexOf(2) !== -1" class="tag-item">二十四小时发货</div>
        <div v-if="goodsInfo?.tags.indexOf(3) !== -1" class="tag-item">四十八小时发货</div>
        <div v-if="goodsInfo?.tags.indexOf(4) !== -1" class="tag-item">假货包赔</div>
      </div>
      <div class="product-detail">
        <div class="product-detail-title">商品详情</div>
        <div class="product-detail-content">{{ goodsInfo?.description }}</div>
      </div>
      <div class="product-imgList-detail">
        <div class="item" v-for="item in goodsInfo?.productImages" :key="item">
          <img :src="item" style="width: 100%;border-radius: 6px;" />

        </div>
      </div>
    </div>
    <div class="product-footer">
      <nut-button type="primary" @click="skipBuy" color="linear-gradient(to right, #5232B7,#7237BC)"
        block>立即购买</nut-button>
    </div>
    <nut-popup v-model:visible="buyModal" position="bottom" round closeable
      :style="{ 'max-height': '80%', 'padding-top': '40px' }">

      <div class="address-info-container">
        <div class="box" v-if="addressInfo?.id" @click="skipAddress">
          <div class="left">
            <IconFont name="location2" color="#999" size="16"></IconFont>
          </div>
          <div class="center">
            <div class="detail">{{ addressInfo?.provinceName }}{{ addressInfo?.cityName }}{{ addressInfo?.areaName }}{{
    addressInfo?.address }}</div>
            <div class="man-info">
              <span class="linkman">{{ addressInfo?.linkman }}</span>
              <span class="phone">{{ addressInfo?.phone }}</span>
            </div>
          </div>
          <div class="right">
            <IconFont name="rect-right" color="#999" size="16"></IconFont>
          </div>
        </div>
        <div class="box" v-else @click="skipAddress">
          <div class="left">
            <IconFont name="location2" color="#999" size="16"></IconFont>
          </div>
          <div class="center">
            请选择收货地址
          </div>
          <div class="right">
            <IconFont name="rect-right" color="#999" size="16"></IconFont>
          </div>
        </div>
      </div>
      <div class="product-header-box">
        <div class="left">
          <image :src="goodsInfo.image" style="width: 100px; border-radius: 8px" mode="widthFix"></image>
        </div>
        <div class="right">
          <div class="price">
            <span class="text1">实付</span>
            <span class="text2"><nut-price :price="totalPrice" size="normal" /></span>
            <nut-divider direction="vertical" />
          </div>
          <div class="number-stock">
            <nut-input-number v-model="goodsNumber" />
          </div>
        </div>
      </div>

      <div class="cate-selected-box">
        <div class="cate-title"> {{ goodsInfo?.masterAttrName }}</div>
        <ul class="cate-list">
          <li class="level1-item" v-for="color in colorOptions" :key="color.value" @click="selectColor(color)"
            :class="{ 'disabled': color.disabled, 'selected': selectedColor === color.value }">
            {{ color.value }}
            <span v-if="color.disabled">(缺货)</span>

          </li>
        </ul>
        <div class="cate-title"> {{ goodsInfo?.slaveAttrName }}</div>

        <ul class="cate-list"
          v-if="filterOptions?.length && goodsInfo?.slaveAttrValues && goodsInfo?.slaveAttrValues.length">
          <li class="level1-item" v-for="(option2, index) in filterOptions" :key="option2.value"
            @click.stop="selectHeight(option2)"
            :class="{ 'disabled': option2.disabled, 'selected': selectedHeight === option2.value }">
            {{ option2.value }}
            <span v-if="option2.disabled">(缺货)</span>
          </li>
        </ul>
        <div class="selected-info" v-if="goodsInfo?.productSpecials && goodsInfo?.productSpecials.length > 1">
          <div class="item">
            <div class="label">
              已选择:
            </div>
            <!-- &&  -->
            <div class="value"
              v-if="(goodsInfo.slaveAttrValues && goodsInfo.slaveAttrValues.length) && (goodsInfo.masterAttrValues && goodsInfo.masterAttrValues.length)">

              <div v-if="selectedColor && selectedHeight">
                {{ selectedColor }} - {{ selectedHeight }}
              </div>
            </div>
            <div class="value"
              v-if="(!goodsInfo.slaveAttrValues) && (goodsInfo.masterAttrValues && goodsInfo.masterAttrValues.length)">
              <div v-if="selectedColor">
                {{ selectedColor }}
              </div>
            </div>
          </div>
        </div>

      </div>

      <div class="footer-btn">
        <nut-button size="normal" block color="linear-gradient(to right, #5232B7,#7237BC)" type="primary"
          @click="payOrder">立即下单</nut-button>
      </div>
    </nut-popup>

  </div>
</template>
<script setup>
import Taro from "@tarojs/taro";
import { ref, reactive, onMounted, watch, computed } from "vue";
import { IconFont } from '@nutui/icons-vue-taro'
import { useLocationStore, useProductStore } from '../../store'
import { storeToRefs } from "pinia";
import {
  toYuan,
  regYuanToFen
} from '../../utils/tools'
import * as productApi from '../../api/product'
import * as addressApi from '../../api/address'
import * as OrderApi from '../../api/order'
const locationStore = useLocationStore();
const productStore = useProductStore();
const { addressInfo } = storeToRefs(locationStore)
const { productInfo, submitInfo } = storeToRefs(productStore)

const router = Taro.useRouter();
const goodsId = ref("");
const buyModal = ref(false);
// 处理后的规格数据
const originalData = ref([]);
const goodsNumber = ref(1);
const colorOptions = ref([])
const heightOptions = ref([])
const filterOptions = ref([])
const selectedColor = ref(null)
const selectedHeight = ref(null)
watch(goodsNumber, (newVal, oldVal) => {
  console.log(newVal, oldVal, "newVal, oldVal");
});

const addressList = ref([]) //地址信息
const goodsInfo = ref({})

onMounted(() => {
  getAddressList()
  goodsId.value = router.params.id;
  getGoodsDetail()
});
//请选择收货地址
const skipAddress = () => {
  Taro.navigateTo({
    url: '/pages/address/index?slected=1'
  })


}
//获取当前用户的地址列表
const getAddressList = async () => {
  try {
    const { data, state, message } = await addressApi.GetAddresses()
    if (state === 200) {
      console.log(data)
      addressList.value = data.map(item => {
        return {
          ...item,
          defaultState: item.defaultState === 1 ? true : false,
          defaultRefundState: item.defaultRefundState === 1 ? true : false
        }
      })
      locationStore.setAddressInfo(data.find(item => item.defaultState === 1));
    } else {
      Taro.showToast({
        title: message,
        icon: 'none'
      })
    }
  } catch (error) {
    console.log(error, "error");
    Taro.showToast({
      title: "获取地址列表失败",
      icon: 'none'
    })
  }
}
//计算一下总价格

const totalPrice = computed(() => {
  if (goodsInfo.value.productType == 0) {
    return toYuan(goodsInfo.value.sellPrice * goodsNumber.value)
  }
  if (goodsInfo.value.productType == 1) {
    let info = originalData.value.find(item => item.masterAttrValue == selectedColor.value)
    if (info && info.sellerPrice) {
      return toYuan(info.sellerPrice * goodsNumber.value)
    }
  }
  if (goodsInfo.value.productType == 2) {
    let info = originalData.value.find(item => item.masterAttrValue == selectedColor.value && item.slaveAttrValue == selectedHeight.value)
    if (info && info.sellerPrice) {
      return toYuan(info.sellerPrice * goodsNumber.value)
    }
  }
})
//计算一下总库存
const totalStock = computed(() => {
  if (goodsInfo.value.productType == 0) {
    return goodsInfo.value.stock
  }
  if (goodsInfo.value.productType == 1 || goodsInfo.value.productType == 2) {
    goodsInfo.value.productSpecials.reduce((total, item) => {
      return total + item.stock

    }, 0)

  }
})
const getGoodsDetail = async () => {
  try {
    const { data, state, message } = await productApi.getProductDetail({ id: goodsId.value })
    if (state === 200) {
      goodsInfo.value = data
      goodsInfo.value.productSpecials = goodsInfo.value.productSpecials.sort((a, b) => a.sellerPrice - b.sellerPrice)

      originalData.value = goodsInfo.value.productSpecials.map(item => {
        return {
          ...item,
          isDisabled: item.stock > 0 ? false : true
        }
      })
      // 商品分为三类  0 没有规格 1 一个规格 2 两个规格 加一个参数 前端自加 方便下单判断   productType
      if (goodsInfo.value.productSpecials.length == 0) {
        goodsInfo.value.productType = 0
      }
      if (goodsInfo.value.masterAttrValues && goodsInfo.value.masterAttrValues.length > 0) {
        goodsInfo.value.productType = 1
      }
      if ((goodsInfo.value.slaveAttrValues && goodsInfo.value.slaveAttrValues.length > 0) && (goodsInfo.value.masterAttrValues && goodsInfo.value.masterAttrValues.length > 0)) {
        goodsInfo.value.productType = 2
      }
      productStore.setProductInfo(goodsInfo.value)
      initOptions()
    } else {
      Taro.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    }

  } catch (error) {
    Taro.showToast({
      title: "获取详情失败~",
      icon: 'none',
      duration: 2000
    })

  }

}

//初始化选择
const initOptions = () => {
  const colorMap = new Map();
  const heightMap = new Map();

  // 首先收集所有颜色和身高选项
  originalData.value.forEach(product => {
    // 处理颜色选项
    if (!colorMap.has(product.masterAttrValue)) {
      colorMap.set(product.masterAttrValue, {
        value: product.masterAttrValue,
        disabled: false, // 初始不禁用
        heights: new Map() // 存储身高和对应的库存
      });
    }
    const colorOption = colorMap.get(product.masterAttrValue);
    colorOption.heights.set(product.slaveAttrValue, product.stock);
    // 处理身高选项
    if (!heightMap.has(product.slaveAttrValue)) {
      heightMap.set(product.slaveAttrValue, {
        value: product.slaveAttrValue,
        disabled: product.stock === 0, // 身高选项的禁用状态基于库存
        colors: new Map() // 存储颜色和对应的库存
      });
    }
    const heightOption = heightMap.get(product.slaveAttrValue);
    heightOption.colors.set(product.masterAttrValue, product.stock);
  });
  // 转换颜色选项：只有当所有身高都缺货时才禁用颜色
  colorOptions.value = Array.from(colorMap.values()).map(color => {
    const hasStock = Array.from(color.heights.values()).some(stock => stock > 0);
    return {
      ...color,
      disabled: !hasStock,
      heights: Array.from(color.heights.entries()).map(([height, stock]) => ({
        value: height,
        stock,
        disabled: stock === 0
      }))
    };
  });
  // 转换身高选项
  heightOptions.value = Array.from(heightMap.values()).map(height => ({
    ...height,
    colors: Array.from(height.colors.entries()).map(([color, stock]) => ({
      value: color,
      stock,
      disabled: stock === 0
    }))
  }));
}
const selectColor = (color) => {
  try {
    if (!color?.disabled) {
      selectedColor.value = color?.value;
      filterOptions.value = color?.heights;
      // 重置身高选择
      selectedHeight.value = null;
    }
  } catch (error) {
    console.log(error, "error");

  }
}
const selectHeight = (height) => {

  try {
    if (!height?.disabled) {
      selectedHeight.value = height?.value;
    }

  } catch (error) {
    console.log(error, "error");
  }
}

//立即下单跳转页面
const payOrder = () => {

  if (!validateOrder()) {
    return
  }
  submitOrder()

};

const submitOrder = async () => {
  let params = {
    "addressId": addressInfo?.value?.id,
    "productCount": goodsNumber.value,
    "productId": goodsId.value,
    "specialId": 0
  }
  if (goodsInfo.value.productType == 1) {
    params.specialId = goodsInfo.value.productSpecials.find(item => item.masterAttrValue == selectedColor.value)?.id
  }
  if (goodsInfo.value.productType == 2) {
    params.specialId = goodsInfo.value.productSpecials.find(item => item.masterAttrValue == selectedColor.value && item.slaveAttrValue == selectedHeight.value)?.id
  }
  try {
    const { data, state, message } = await OrderApi.SubmitCommerceOrder(params)
    if (state == 200) {
      if (data?.orderNumber) {
        productStore.setSubmitInfo(data)
        Taro.redirectTo({
          url: `/pages/goods-payDetail/index`,
        });
      }


    } else {
      Taro.showToast({
        title: message,
        icon: 'none',
        duration: 2000

      })
    }
  } catch (error) {
    console.log(error, "error");

  }

}

//羽然图片
const handlePreviewImage = (item) => {
  Taro.previewImage({
    current: item, // 当前显示图片的http链接
    urls: goodsInfo?.value.productImages, // 需要预览的图片http链接列表
  });
};

const validateOrder = () => {
  if (goodsInfo.value.productType == 0) {
    return true

  } else if (goodsInfo.value.productType == 1) {
    if (!selectedColor.value) {
      if (goodsInfo.value.masterAttrName) {
        Taro.showToast({
          title: `请选择${goodsInfo.value.masterAttrName}！`,
          icon: 'none',
          duration: 2000
        })
        return false

      } else {
        Taro.showToast({
          title: `请选择规格！`,
          icon: 'none',
          duration: 2000

        })
        return false
      }
    }

  } else if (goodsInfo.value.productType == 2) {
    if (!selectedColor.value && !selectedHeight.value) {
      if (goodsInfo.value.masterAttrName && goodsInfo.value.slaveAttrName) {
        Taro.showToast({
          title: `请选择${goodsInfo.value.masterAttrName}-${goodsInfo.value.slaveAttrName}！`,
          icon: 'none',
          duration: 2000

        })
        return false

      } else {
        Taro.showToast({
          title: `请选择完整规格！`,
          icon: 'none',
          duration: 2000

        })
        return false
      }
    }
    if (selectedColor.value && !selectedHeight.value) {
      if (goodsInfo.value.slaveAttrName) {
        Taro.showToast({
          title: `请选择${goodsInfo.value.slaveAttrName}！`,
          icon: 'none',
          duration: 2000

        })
        return false

      } else {
        Taro.showToast({
          title: `请选择完整规格！`,
          icon: 'none',
          duration: 2000

        })
        return false
      }
    }

  }

  //检查购买数量
  if (goodsNumber.value <= 0) {
    Taro.showToast({
      title: `数量必须大于0！`,
      icon: 'none',
      duration: 2000

    })
    return false
  }
  //检查收货地址
  if (!addressInfo?.value?.id) {
    Taro.showToast({
      title: `请选择收货地址！`,
      icon: 'none',
      duration: 2000

    })
    return false
  }

  return true
}
const skipBuy = async () => {
  // if (originalData.value.length) {
  buyModal.value = true;

  // } 
};
</script>
<style lang="scss">
page {
  background-color: #fff;
}

li {
  list-style: none;
  padding: 0;
  margin: 0;
}

ul {
  padding: 0;
  margin: 0;
}


.goods-detail-caontainer {
  .address-info-container {
    border-bottom: 1px solid #f7f8f9;
    padding: 50px 20px;


    .box {
      display: flex;
      align-items: center;
      // justify-content: space-between;

      .center {
        font-size: 24px;
        width: 80%;
        text-align: left;

        .detail {
          font-weight: 600;
          font-size: 26px;
        }

        .man-info {
          margin-top: 10px;

          .linkman {}

          .phone {
            margin-left: 10px;
          }

        }

      }

      .left {
        width: 10%;
      }

      .right {
        width: 10%;
      }
    }

  }

  // padding: 10px;
  .cate-selected-box {
    padding: 0 20px;

    .cate-title {
      font-weight: 700;
      margin: 10px 0;
      font-size: 26px;
    }

    .selected-info {
      margin: 15px;
      margin-top: 25px;

      .item {
        display: flex;
        align-items: center;
        font-size: 24px;

        .label {
          color: #858a99;
        }

        .value {
          color: #6034b9;
          margin-left: 10px;
        }
      }
    }



    .cate-list {
      cursor: pointer;
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .level1-item {
        padding: 10px 20px;
        border: 1px solid #ccc;
        border-radius: 5px;
        transition: all 0.3s;
        margin: 6px;
        font-size: 24px;
      }

      .level1-item:hover {
        border: 1px solid #6034b9;
      }

      .level1-item:nth-child(n+2) {
        // margin-left: 10px;
        // margin: 10px;
      }
    }
  }

  .disabled {
    color: #ccc;
    cursor: not-allowed;
  }

  .selected {
    background-color: #6034b9;
    color: white;
    border-color: #6034b9;
  }

  .footer-btn {
    padding: 30px;
  }

  .product-header-box {
    display: flex;
    padding: 0 20px;
    margin-top: 20px;

    .left {}

    .right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 25px;

      .price {
        .text1 {
          font-size: 24px;
          color: red;
          margin-right: 15px;
        }
      }

      .number-stock {
        margin-top: 30px;
      }
    }
  }

  .spec-selector {
    padding: 15px;
    border: 1px solid #f7f8f9;
    border-radius: 4px;
    margin-top: 15px;
    font-size: 24px;
    // background-color: pink;

    .spec-group {
      margin-bottom: 20px;

      .spec-title {
        font-weight: bold;
        margin-bottom: 10px;
      }

      .spec-items {
        display: flex;
        overflow-x: auto;
        flex-wrap: wrap;

        // gap: 10px;
        .spec-item {
          padding: 8px 15px;
          border: 1px solid #ddd;
          max-width: 180px;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.3s;
          margin-top: 10px;
          margin-left: 10px;
        }

        .spec-item:hover {
          border-color: #6034b9;
        }

        .spec-item.active {
          // background-color: #6034b9;
          color: #6034b9;
          border-color: #6034b9;
        }
      }
    }
  }

  .selected-info {
    margin-top: 20px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
  }

  .product-footer {
    padding: 10px 35px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .goods-detail-content {
    background-color: #fff;
    padding: 15px;

    .price-box {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .stock {
        font-size: 26px;
        color: #999;
      }
    }

    .product-title {
      // height: 80px;
      color: #15181d;
      font-size: 28px;
      font-weight: 700;
    }

    .product-tags {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 15px;

      .tag-item {
        font-size: 24px;
        color: #999;
        padding: 5px 10px;
        border-radius: 20px;
        background-color: #f5f5f5;
      }
    }

    .product-detail {
      .product-detail-title {
        font-size: 28px;
        font-weight: 700;
        margin-top: 25px;
      }

      .product-detail-content {
        margin-top: 15px;
        font-size: 24px;
        color: #999;
      }
    }

    .product-imgList-detail {
      display: flex;
      flex-direction: column;
      align-items: center;
      // padding: 10px;
      margin-top: 30px;

      .item {
        padding: 0 10px;
        width: 90%;
        display: flex;
        justify-content: center;
        align-items: center;

      }

      .item:nth-child(n+2) {
        margin-top: 20px;
      }
    }
  }
}
</style>
